<?php
namespace Lib;

class Sms{

    public $smsSign = '【客服】'; //短信签名
    public $status_code; //发送短信状态码
    public $error_msg; //错误原因
    public $error_num = 0; //错误次数
    public $num;    //发送条数;
    public $order_num; //账单号;
    public $sms_company;//提供商
    private $timeout = 5;//超时时间
    protected $statuArr;

    //调用短信平台 - 发送短信的方法, 默认发送的放在第一个
    public $sendFunctions = array(
        'ytx_sms',//容联云通讯, 需要提交短信模板备案
        'emay_sms', //亿美
        'ay_sms', //奥易互通
        //'hywx_sms', //互亿无线 ,需要提交短信模板备案
         //'ytx_call', //云通讯语音
    );

    public $config=array(

        //奥易互通
        'ay_sms'=>array(
            'username'=>'lczx01', //短信提供商用户名
            'password'=>'430123', //密码

            'username2' => 'lczx02',
            'password2' => '430234',

			'username3' => 'lczx03',
            'password3' => '430345',

			'username4' => 'lczx04',
            'password4' => '430456',

			'username5' => 'lczx05',
            'password5' => '430567',

            'username6' => 'bjfnyd',
            'password6' => '898123',

            'url'=>'http://101.200.228.238/smsport/default.asmx/SendSms', //短信提交地址
            'longnum'=>'0130',
            'longnum2'=>'0197',
			'longnum3'=>'9831',
			'longnum4'=>'5810',
			'longnum5'=>'5862',
            'longnum6'=>'9185',
            'statusArr' =>array(   //错误状态码
                '-1' => '帐号和密码验证失败或是帐号被注销',
                '-2' => '手机号码为空或含有不合法的手机号码',
                '-3' => '内容为空或含有非法字符',
                '-4' => '账号余额不足',
                '-5' => 'longnum不合法',
                '-10' => '其他错误',
            ),
        ),

        //亿美
        'emay_sms'=>array(
            'cdkey'=>'6SDK-EMY-6688-KKWUL',
            'password'=>'654863',
            'url'=>'http://sdk4report.eucp.b2m.cn:8080/sdkproxy/sendsms.action',
            'statusArr' =>array(   //错误状态码
                305=>'服务器端返回错误，错误的返回值（返回值不是数字字符串）',
                101=>'客户端网络故障',
                303=>'客户端网络故障',
                307=>'目标电话号码不符合规则，电话号码必须是以0、1开头',
                997=>'平台返回找不到超时的短信，该信息是否成功无法确定',
                998=>'由于客户端网络问题导致信息发送超时，该信息是否成功下发无法确定',

                0=>	'服务器端	成功',
                -2=>'客户端	客户端异常',

                -9000=>'数据格式错误,数据超出数据库允许范围',
                -9001=>'客户端,所有业务	序列号格式错误',
                -9002=>'客户端,所有业务	密码格式错误',
                -9003=>'客户端,所有业务	客户端Key格式错误',
                -9004=>'客户端,转发业务	设置转发格式错误',
                -9005=>'客户端,企业注册业务	公司地址格式错误',
                -9006=>'客户端,企业注册业务	企业中文名格式错误',
                -9007=>'客户端,企业注册业务	企业中文名简称格式错误',
                -9008=>'客户端,企业注册业务	邮件地址格式错误',
                -9009=>'客户端,企业注册业务	企业英文名格式错误',
                -9010=>'客户端,企业注册业务	企业英文名简称格式错误',
                -9011=>'客户端,企业注册业务	传真格式错误',
                -9012=>'客户端,企业注册业务	联系人格式错误',
                -9013=>'客户端,企业注册业务	联系电话',
                -9014=>'客户端,企业注册业务	邮编格式错误',
                -9015=>'客户端,密码修改业务	新密码格式错误',
                -9016=>'客户端,发送业务	发送短信包大小超出范围',
                -9017=>'客户端,发送业务	发送短信内容格式错误',
                -9018=>'客户端,发送业务	发送短信扩展号格式错误',
                -9019=>'客户端,发送业务	发送短信优先级格式错误',
                -9020=>'客户端,发送业务	发送短信手机号格式错误',
                -9021=>'客户端,发送业务	发送短信定时时间格式错误',
                -9022=>'客户端,发送业务	发送短信唯一序列值错误',
                -9023=>'客户端,充值业务	充值卡号格式错误',
                -9024=>'客户端,充值业务	充值密码格式错误',
                -9025=>'客户端	客户端请求sdk5超时（需确认）',

                -1=>'服务器端	系统异常',
                -101=>'服务器端	命令不被支持',
                -102=>'服务器端	RegistryTransInfo删除信息失败（转接）',
                -103=>'服务器端	RegistryInfo更新信息失败（序列号相关注册）',
                -104=>'服务器端	请求超过限制',
                -111=>'服务器端	企业注册失败',
                -117=>'服务器端	发送短信失败',
                -118=>'服务器端	接收MO失败',
                -119=>'服务器端	接收Report失败',
                -120=>'服务器端	修改密码失败',
                -122=>'服务器端	号码注销失败',
                -110=>'服务器端	号码注册激活失败',
                -123=>'服务器端	查询单价失败',
                -124=>'服务器端	查询余额失败',
                -125=>'服务器端	设置MO转发失败',
                -126=>'服务器端	路由信息失败',
                -127=>'服务器端	计费失败0余额',
                -128=>'服务器端	计费失败余额不足',

                -1100=>'服务器端	序列号错误,序列号不存在内存中,或尝试攻击的用户',
                -1103=>'服务器端	序列号Key错误',
                -1102=>'服务器端	序列号密码错误',
                -1104=>'服务器端	路由失败，请联系系统管理员',
                -1105=>'服务器端	注册号状态异常, 未用 1',
                -1107=>'服务器端	注册号状态异常, 停用 3',
                -1108=>'服务器端	注册号状态异常, 停止 5',

                -113=>'服务器端	充值失败',
                -1131=>'服务器端	充值卡无效',
                -1132=>'服务器端	充值密码无效',
                -1133=>'服务器端	充值卡绑定异常',
                -1134=>'服务器端	充值状态无效',
                -1135=>'服务器端	充值金额无效',

                -190=>'服务器端	数据操作失败',
                -1901=>'服务器端	数据库插入操作失败',
                -1902=>'服务器端	数据库更新操作失败',
                -1903=>'服务器端	数据库删除操作失败',
            ),
        ),

        //互亿无线
        'hywx_sms'=>array(
            'username'=>'cf_qianyi', //短信提供商用户名
            'password'=>'123456', //密码
            'url'=>'http://106.ihuyi.cn/webservice/sms.php', //短信提交地址
            'statusArr' =>array(   //错误状态码
                0=>'提交失败',
                2=>'提交成功',
                400=>'非法ip访问',
                401=>'帐号不能为空',
                402=>'密码不能为空',
                403=>'手机号码不能为空',
                4030=>'手机号码已被列入黑名单',
                404=>'短信内容不能为空',
                405=>'用户名或密码不正确',
                4050=>'账号被冻结',
                4051=>'剩余条数不足',
                4052=>'访问ip与备案ip不符',
                406=>'手机格式不正确',
                407=>'短信内容含有敏感字符',
                4070=>'签名格式不正确',
                4071=>'没有提交备案模板',
                4072=>'短信内容与模板不匹配',
                4073=>'短信内容超出长度限制',
                408=>'您的帐户疑被恶意利用，已被自动冻结，如有疑问请与客服联系',
            ),
        ),

        //云通讯
        'ytx_sms'=>array(
            //sandbox
            // 'serverIP'      =>'sandboxapp.cloopen.com', //ip
            // 'serverPort'    =>'8883', //端口
            // 'softVersion'   => '2013-12-26',
            // 'accountSid'    => 'aaf98f89512446e201513395f9942f6d',
            // 'accountToken'  => 'e503f8a7a8604b4cbedd787a64eb8e2c',
            // 'appId'         => '8a48b55151245988015133963e102f38',

            'serverIP'      =>'app.cloopen.com', //ip
            'serverPort'    =>'8883', //端口
            'softVersion'   => '2013-12-26',
            'accountSid'    => 'aaf98f89512446e201513395f9942f6d',
            'accountToken'  => 'e503f8a7a8604b4cbedd787a64eb8e2c',
            'appId'         => 'aaf98f89512446e2015133b295da3013',
	   ),

        //云通讯语音
        'ytx_call'=>array(
            //sandbox
            // 'serverIP'      =>'sandboxapp.cloopen.com', //ip
            // 'serverPort'    =>'8883', //端口
            // 'softVersion'   => '2013-12-26',
            // 'accountSid'    => 'aaf98f89512446e201513395f9942f6d',
            // 'accountToken'  => 'e503f8a7a8604b4cbedd787a64eb8e2c',
            // 'appId'         => '8a48b55151245988015133963e102f38',

            'serverIP'      =>'app.cloopen.com', //ip
            'serverPort'    =>'8883', //端口
            'softVersion'   => '2013-12-26',
            'accountSid'    => 'aaf98f89512446e201513395f9942f6d',
            'accountToken'  => 'e503f8a7a8604b4cbedd787a64eb8e2c',
            'appId'         => 'aaf98f89512446e2015133b295da3013',
       ),
        
    ); //配置信息
    
    
    public function send($phonelist,$msg, $marketing = 0)
    {
        //生产环境才可以发短信
        if($_SERVER['ENV_NAME']!='product' && APP_DEBUG != true)
        {
            return true;
        }

        if(empty($phonelist) || empty($msg)) return false;

        foreach ($this->config as $k=>$v){
            $func = $k;
            $bool = $this->$func($phonelist,$msg, $marketing);
            if($bool) return true;

            $this->error_num =+ 1;
        }

        return FALSE;
    }
    
    /**
     * 奥易互通
     * @param int type 发送类型 1调取发送推广短信的通道
     */
    public function ay_sms($phonelist,$msg, $type = 0, $options = array())
    {
        $this->sms_company = __FUNCTION__;
		//生产环境才可以发短信
        if($_SERVER['ENV_NAME']!='product' && APP_DEBUG != true)
        {
            return true;
        }
        if($type)
        {
            //推广短信
            $data['username'] = $this->config['ay_sms']['username2'];//系统分配的用户帐号
            $data['password'] = $this->config['ay_sms']['password2'];//系统分配的用户密码
            $data['longnum'] = $this->config['ay_sms']['longnum2'];
        }
        else
        {
            $data['username'] = $this->config['ay_sms']['username6'];//系统分配的用户帐号
            $data['password'] = $this->config['ay_sms']['password6'];//系统分配的用户密码
            $data['longnum'] = $this->config['ay_sms']['longnum6'];
        }
        
        $data['phonelist'] = $phonelist;

        // var_dump($data);exit;
        // var_dump(mb_strlen($msg,'utf8'));exit;

        // if(mb_strlen($msg,'utf8') > 67)
        // {
        //     $this->error_msg = "too long";
        //     return false;
        // }

        $data['msg'] = $msg;
        //$time1 = gettimeofday(true);
        $code =  \Org\Net\Http::_post($this->config['ay_sms']['url'], $data, $this->timeout);
        //echo "|",__FUNCTION__,':',gettimeofday(true) - $time1 , '|';
        //var_dump($code);
        $code = (array) simplexml_load_string($code);
        
        $code = $code[0];
        
        if(!strpos($code,'|')){
            
            if(!empty($this->config[__FUNCTION__]['statusArr'])){
            
                $this->status_code = $code;
                
                $this->error_msg = $this->config[__FUNCTION__]['statusArr'][$code];
                
            }else{
                
                $this->status_code = 0;
                
                $this->error_msg = $code;
                
            }
            
            return false;
        }else{
            $this->status_code = 1;
            list($this->num,$this->order_num) = explode('|', $code);

            return true;
        }
        
    }

    //亿美短信
    public function emay_sms($phonelist,$msg, $type = 0, $options = array())
    {
        $this->sms_company = __FUNCTION__;
		//生产环境才可以发短信
        if($_SERVER['ENV_NAME']!='product')
        {
            return true;
        }
        $data['cdkey'] = $this->config['emay_sms']['cdkey'];
        $data['password'] = $this->config['emay_sms']['password'];
        $data['phone'] = is_array($phonelist)?implode(',',$phonelist):$phonelist;
        $data['message'] = $this->smsSign.trim($msg);

        $opts['http'] = array(
            'method' => 'get',
            'timeout'=> $this->timeout, //超时时间，单位为秒
        );
        $context = stream_context_create($opts);
        $url = $this->config['emay_sms']['url'].'?'.http_build_query($data);

        $xml = file_get_contents($url, false, $context);
        $redata = json_decode(json_encode(simplexml_load_string(trim($xml))),1);
        foreach($redata as &$rd){
            empty($rd) && $rd = '';
        }

        $this->status_code = intval($redata['error']);
        $this->error_msg = trim($redata['message']);
        empty($this->error_msg) && $this->error_msg = $this->config[__FUNCTION__]['statusArr'][trim($this->status_code)];
        $this->num = count(explode(',',$data['phone'])); //成功条数

        return !$this->status_code;
    }

    /*
     * 互亿无线
     */
    public function hywx_sms($phonelist,$msg, $marketing = 0, $options = array())
    {
        $this->sms_company = __FUNCTION__;
		//生产环境才可以发短信
        if($_SERVER['ENV_NAME']!='product')
        {
            return true;
        }
        if(!is_array($phonelist)){
            $phonelist = explode(',',$phonelist);
        }
        $data = array(
            'method'=>'Submit',
            'account'=>$this->config['hywx_sms']['username'],
            'password'=>$this->config['hywx_sms']['password'],
            'content'=>$msg,
        );

        $n = 0; //发送成功计数器
        foreach($phonelist as $mobile){
            $data['mobile'] = trim($mobile);
            $url = $this->config['hywx_sms']['url'].'?'.http_build_query($data);
            //$time1 = gettimeofday(true);
            $context = stream_context_create(array(
                'http' => array(
                    'method' => 'get',
                    'timeout' => $this->timeout, //超时时间，单位为秒
                )
            ));
            $xml = file_get_contents($url, 0, $context);
            //echo "|",__FUNCTION__,':',gettimeofday(true) - $time1 , '|';
            //var_dump($xml);
            $redata = (array)simplexml_load_string($xml);
            if((int)$redata['code']==2){
                $n++;
            }
        }

        $this->status_code = $redata['code'];
        $this->error_msg = $redata['msg'];
        $this->num = $n; //成功条数

        return $n?true:false;
    }

    /*
     * 容联云通讯
     */
    public function ytx_sms($phonelist,$msg, $marketing = 0, $options = array())
    {
        $this->sms_company = __FUNCTION__;
		//生产环境才可以发短信
        if($_SERVER['ENV_NAME']!='product')
        {
            return true;
        }
        $rest = new \Lib\SmsDriver\Ytx\Sms\Ccp($this->config['ytx_sms']['serverIP'],
            $this->config['ytx_sms']['serverPort'],
            $this->config['ytx_sms']['softVersion']);
        $rest->setAccount($this->config['ytx_sms']['accountSid'], $this->config['ytx_sms']['accountToken']); 
        $rest->setAppId($this->config['ytx_sms']['appId']); 

        $tempId = $rest->getTmpId($options['type']);//取模板id
        $datas = $rest->getTmpData($options['type'], $options['data']);//组装数据

        // 发送模板短信
        //echo "Sending TemplateSMS to $phonelist <br/>";
        $result = $rest->sendTemplateSMS($phonelist, $datas, $tempId);
        if($result == NULL ) {
            $this->status_code = 0;
            $this->error_msg = "result error!";
            $this->num = 0;
            return false;
        }
        if($result->statusCode!=0) {
            $this->status_code = (string)$result->statusCode;
            $this->error_msg = (string)$result->statusMsg;
            $this->num = 0; 
            return false;
        }else{
            //echo "Sendind TemplateSMS success!<br/>";
            // 获取返回信息
            $smsmessage = $result->TemplateSMS;
            //echo "dateCreated:".$smsmessage->dateCreated."<br/>";
            //echo "smsMessageSid:".$smsmessage->smsMessageSid."<br/>";
            $this->status_code = 1;
            $this->error_msg = "";
            $this->num = count(explode(",", $phonelist));
            return true;
        }
    }

    /*
     * 容联云通讯(语音)
     */
    public function ytx_call($phonelist, $msg, $marketing = 0, $options = array())
    {
        //记录日志 add by shang 2016 04 15
        \Lib\Log::debuglog("sms", array_merge(array(
            'url'=>$_SERVER['SCRIPT_URI'],
            'ip'=>$_SERVER["HTTP_X_FORWARDED_FOR"],
        ), $_GET, $_POST));

        $this->sms_company = __FUNCTION__;
        //生产环境才可以发短信
        if($_SERVER['ENV_NAME']!='product')
        {
            return true;
        }
        //只接受1个号码
        if(strpos($phonelist, ',') !== false)
        {
            $phonelist = array_shift(explode(",", $phonelist));
        }

        $rest = new \Lib\SmsDriver\Ytx\Voice\Ccp($this->config['ytx_sms']['serverIP'],
            $this->config['ytx_sms']['serverPort'],
            $this->config['ytx_sms']['softVersion']);
        $rest->setAccount($this->config['ytx_sms']['accountSid'], $this->config['ytx_sms']['accountToken']); 
        $rest->setAppId($this->config['ytx_sms']['appId']); 

        // 发送模板短信
        // echo "Try to make a voiceverify,called is $to <br/>";
        $result = $rest->voiceVerify(
            $options['data']['code'],
            3,
            $phonelist,
            '4009101001',
            "",
            "zh",
            "",
            "",
            "");
        if($result == NULL ) {
            $this->status_code = 0;
            $this->error_msg = "result error!";
            $this->num = 0;
            return false;
        }
        if($result->statusCode!=0) {
            $this->status_code = (string)$result->statusCode;
            $this->error_msg = (string)$result->statusMsg;
            $this->num = 0; 
            return false;
        }else{
            // echo "voiceverify success!<br>";
            // 获取返回信息
            $voiceVerify = $result->VoiceVerify;
            // echo "callSid:".$voiceVerify->callSid."<br/>";
            // echo "dateCreated:".$voiceVerify->dateCreated."<br/>";
            $this->status_code = 1;
            $this->error_msg = (string)$voiceVerify->callSid;
            $this->num = 1;
            return true;
        }
    }

	/**
     * 奥易互通 为 集团正润金控使用
     * @param int type 发送类型 1调取发送推广短信的通道
     */
    public function ay_sms1($phonelist,$msg, $type = 0, $options = array())
    {
		$this->sms_company = __FUNCTION__;
        //生产环境才可以发短信
		/*
        if($_SERVER['ENV_NAME']!='product')
        {
            return true;
        }
		*/
		//正润金控账号
		$data['username'] = $this->config['ay_sms']['username3'];//系统分配的用户帐号
		$data['password'] = $this->config['ay_sms']['password3'];//系统分配的用户密码
		$data['longnum'] = $this->config['ay_sms']['longnum3'];
        $data['phonelist'] = $phonelist;
        $data['msg'] = $msg;
        //$time1 = gettimeofday(true);
        $code =  \Org\Net\Http::_post($this->config['ay_sms']['url'], $data, $this->timeout);
        //echo "|",__FUNCTION__,':',gettimeofday(true) - $time1 , '|';
        //var_dump($code);
        $code = (array) simplexml_load_string($code);
        $code = $code[0];
        if(!strpos($code,'|'))
		{
            if(!empty($this->config[__FUNCTION__]['statusArr']))
			{
                $this->status_code = $code;
                $this->error_msg = $this->config[__FUNCTION__]['statusArr'][$code];
            }
			else
			{
                $this->status_code = 0;
                $this->error_msg = $code;
            }
            return false;
        }
		else
		{
            $this->status_code = 1;
            list($this->num,$this->order_num) = explode('|', $code);
            return true;
        }
    }

	
	/**
     * 奥易互通 为 集团正润金控-宜江投资使用
     * @param int type 发送类型 1调取发送推广短信的通道
     */
    public function ay_sms2($phonelist,$msg, $type = 0, $options = array())
    {
		$this->sms_company = __FUNCTION__;
        //生产环境才可以发短信
		/*
        if($_SERVER['ENV_NAME']!='product')
        {
            return true;
        }
		*/
		//正润金控账号
		$data['username'] = $this->config['ay_sms']['username4'];//系统分配的用户帐号
		$data['password'] = $this->config['ay_sms']['password4'];//系统分配的用户密码
		$data['longnum'] = $this->config['ay_sms']['longnum4'];
        $data['phonelist'] = $phonelist;
        $data['msg'] = $msg;
        //$time1 = gettimeofday(true);
        $code =  \Org\Net\Http::_post($this->config['ay_sms']['url'], $data, $this->timeout);
        //echo "|",__FUNCTION__,':',gettimeofday(true) - $time1 , '|';
        //var_dump($code);
        $code = (array) simplexml_load_string($code);
        $code = $code[0];
        if(!strpos($code,'|'))
		{
            if(!empty($this->config[__FUNCTION__]['statusArr']))
			{
                $this->status_code = $code;
                $this->error_msg = $this->config[__FUNCTION__]['statusArr'][$code];
            }
			else
			{
                $this->status_code = 0;
                $this->error_msg = $code;
            }
            return false;
        }
		else
		{
            $this->status_code = 1;
            list($this->num,$this->order_num) = explode('|', $code);
            return true;
        }
    }
	
	/**
     * 奥易互通 为 联储证券使用
     * @param int type 发送类型 1调取发送推广短信的通道
     */
    public function ay_sms3($phonelist,$msg, $type = 0, $options = array())
    {
		$this->sms_company = __FUNCTION__;
        //生产环境才可以发短信
		/*
        if($_SERVER['ENV_NAME']!='product')
        {
            return true;
        }
		*/
		//正润金控账号
		$data['username'] = $this->config['ay_sms']['username5'];//系统分配的用户帐号
		$data['password'] = $this->config['ay_sms']['password5'];//系统分配的用户密码
		$data['longnum'] = $this->config['ay_sms']['longnum5'];
        $data['phonelist'] = $phonelist;
        $data['msg'] = $msg;
        //$time1 = gettimeofday(true);
        $code =  \Org\Net\Http::_post($this->config['ay_sms']['url'], $data, $this->timeout);
        //echo "|",__FUNCTION__,':',gettimeofday(true) - $time1 , '|';
        //var_dump($code);
        $code = (array) simplexml_load_string($code);
        $code = $code[0];
        if(!strpos($code,'|'))
		{
            if(!empty($this->config[__FUNCTION__]['statusArr']))
			{
                $this->status_code = $code;
                $this->error_msg = $this->config[__FUNCTION__]['statusArr'][$code];
            }
			else
			{
                $this->status_code = 0;
                $this->error_msg = $code;
            }
            return false;
        }
		else
		{
            $this->status_code = 1;
            list($this->num,$this->order_num) = explode('|', $code);
            return true;
        }
    }
	
    public static function getInstance()
    {
        
        static $class = NULL;
        
        if($class == NULL)
            
            $class = new self();
        
        return $class;
    }
    
}
